<?php
namespace lib\wechat;

class WechatAppPay {
	//接口API URL前缀
	const API_URL_PREFIX = 'https://api.mch.weixin.qq.com';
	// 退款
    const API_REFUND = '/secapi/pay/refund';
	// 退款查询
    const API_QUERY_REFUND = '/pay/refundquery';
	//提现到微信
	const API_TRANSFERS = "/mmpaymkttransfers/promotion/transfers";
	//获取RSA加密公钥API
	const API_GETPUBLICKEY = "https://fraud.mch.weixin.qq.com/risk/getpublickey";
	//提现到银行
	const API_PAY_BANK = "/mmpaysptrans/pay_bank";
	//下单地址URL
	const UNIFIEDORDER_URL = "/pay/unifiedorder";
	//查询订单URL
	const ORDERQUERY_URL = "/pay/orderquery";
	//关闭订单URL
	const CLOSEORDER_URL = "/pay/closeorder";
	//请求分账API
	const PROFITSHARING_URL = "/secapi/pay/profitsharing";
	//添加分账接收方
	const ADD_RECEIVER_URL = "/pay/profitsharingaddreceiver";
	//完结分账
	const PROFITSHARINGFINISH_URL = "/pay/profitsharingfinish";
	//沙盒模式
	protected $sandboxEnabled = false;
	//公众账号ID
	private $appid;
	//商户号
	private $mch_id;
	//随机字符串
	private $nonce_str;
	//签名
	private $sign;
	//商品描述
	private $body;
	//商户订单号
	private $out_trade_no;
	//支付总金额
	private $total_fee;
	//退款价格
	private $refund_fee;
	//终端IP
	private $spbill_create_ip;
	//支付结果回调通知地址
	private $notify_url;
	//交易类型
	private $trade_type;
	//支付密钥
	private $key;
	//证书路径
	private $SSLCERT_PATH;
	private $SSLKEY_PATH;
	private $PUBKEY;
	private $NEW_PUBKEY;
	
	//所有参数
	private $params = array();
	public function __construct($appid, $mch_id, $notify_url,$key,$cacert,$sub_mchid,$sub_appid) {
		$this -> appid = $appid;
		$this -> mch_id = $mch_id;
		$this -> notify_url = $notify_url;
		$this -> key = $key;
		$this -> sub_mch_id = $sub_mchid;
		$this -> sub_appid = $sub_appid;
		$this -> nonce_str = $this -> genRandomString();
		$this -> spbill_create_ip = $_SERVER['REMOTE_ADDR'];
		$this -> SSLCERT_PATH = $cacert.'/apiclient_cert.pem';
		$this -> SSLKEY_PATH = $cacert.'/apiclient_key.pem';
		$this -> PUBKEY = $cacert.'/pubkey.pem';
		$this -> NEW_PUBKEY = $cacert.'/pubkey_new.pem';
	}

	/**
	 * 下单方法
	 * @param $params 下单参数
	 */
	public function unifiedOrder($params) {
		$params['appid'] = $this -> appid;
		$params['mch_id'] = $this -> mch_id;
		$params['nonce_str'] = $this -> nonce_str;
		$params['notify_url'] = $this -> notify_url;
		$params['spbill_create_ip'] = $this -> spbill_create_ip;
		if($this->sub_mch_id){
			$params['sub_mch_id'] = $this->sub_mch_id;
		}
		if($this->sub_appid){
			$params['sub_appid'] = $this->sub_appid;
		}
		$params['attach'] = $params['attach'] ?: "商品订单";
		$params['body'] = $params['body'];
		$params['out_trade_no'] = $params['out_trade_no'];
		$params['total_fee'] = $params['total_fee'];
		$params['trade_type'] = $params['trade_type'];
		if($params['openid']){
			$params['openid'] = $params['openid'];
		}
		$params['profit_sharing'] = $params['profit_sharing'] ?: 'N';
		
		//获取签名数据
		$params['sign'] = $this -> MakeSign($params);
		$xml = $this -> data_to_xml($params);
		$response = $this -> postXmlCurl($xml, self::API_URL_PREFIX . self::UNIFIEDORDER_URL);
		if (!$response) {
			return false;
		}
		$result = $this -> xml_to_data($response);
		if (!empty($result['result_code']) && !empty($result['err_code'])) {
			$result['err_msg'] = $this -> error_code($result['err_code']);
		}
		return $result;
	}


	/**
	 * 查询订单信息
	 * @param $out_trade_no 订单号
	 * @return array
	 */
	public function orderQuery($out_trade_no) {
		$params['appid'] = $this -> appid;
		$params['mch_id'] = $this -> mch_id;
		$params['nonce_str'] = $this -> genRandomString();
		$params['out_trade_no'] = $out_trade_no;
		if($this->sub_mch_id){
			$params['sub_mch_id'] = $this->sub_mch_id;
		}
		if($this->sub_appid){
			$params['sub_appid'] = $this->sub_appid;
		}
		//获取签名数据
		$params['sign'] = $this -> MakeSign($params);
		$xml = $this -> data_to_xml($params);
		$response = $this -> postXmlCurl($xml, self::API_URL_PREFIX . self::ORDERQUERY_URL);
		if (!$response) {
			return false;
		}
		$result = $this -> xml_to_data($response);
		if (!empty($result['result_code']) && !empty($result['err_code'])) {
			$result['err_msg'] = $this -> error_code($result['err_code']);
		}
		return $result;
	}
	
	
	/**
	 * 添加分账接收方
	 * @param $params 参数
	 */
	public function profitsharing_addreceiver($receivers) {
		$params['appid'] = $this -> appid;
		$params['mch_id'] = $this -> mch_id;
		$params['nonce_str'] = $this -> nonce_str;
		if($this->sub_mch_id){
			$params['sub_mch_id'] = $this->sub_mch_id;
		}
		if($this->sub_appid){
			$params['sub_appid'] = $this->sub_appid;
		}
		$params['receiver'] = json_encode($receivers,true);
		//获取签名数据
		$params['sign'] = $this -> MakeSignHash($params);
		$xml = $this -> data_to_xml($params);
		$response = $this -> postXmlCurl($xml,self::API_URL_PREFIX.self::ADD_RECEIVER_URL);
		return $this -> xml_to_data($response);
	}
	
	
	/**
	 * 分账
	 * @param $params 参数
	 */
	public function profitSharing($out_trade_no,$transaction_id,$receivers) {
		//1.添加分账接收方
		foreach($receivers as $key => $value){
			$res = self::profitsharing_addreceiver([
				"type"=>$value['type'],
		      	"account"=>$value['account'],
		      	"relation_type"=>"OTHERS",
			]);
			if ( $res['return_msg'] ) {
				$result['result_code'] == 'FAIL';
				$result['err_msg'] = $res['return_msg'];
				return $result;
			}
		}
		//2.分账
		$params['appid'] = $this -> appid;
		$params['mch_id'] = $this -> mch_id;
		$params['nonce_str'] = $this -> nonce_str;
		if($this->sub_mch_id){
			$params['sub_mch_id'] = $this->sub_mch_id;
		}
		if($this->sub_appid){
			$params['sub_appid'] = $this->sub_appid;
		}
		$params['transaction_id'] = $transaction_id;
		$params['out_order_no'] = $out_trade_no;
		$params['receivers'] = json_encode($receivers,true);

		//获取签名数据
		$params['sign'] = $this -> MakeSignHash($params);
		$xml = $this -> data_to_xml($params);
		$response = $this -> postXmlCurl($xml, self::API_URL_PREFIX.self::PROFITSHARING_URL,true);
		if (!$response) {
			$result['result_code'] == 'FAIL';
			$result['err_code'] = '';
			$result['err_msg'] = "错误，请检查支付证书是否有效！";
			return $result;
		}
		$result = $this -> xml_to_data($response);
		if (!empty($result['result_code']) && !empty($result['err_code'])) {
			$result['err_msg'] = $result['err_code_des'];
		}
		return $result;
	}
	
	
	/**
	 * 完结分账
	 * @param $params 参数
	 */
	public function profitsharingfinish($out_order_no,$transaction_id) {
		$params['appid'] = $this -> appid;
		$params['mch_id'] = $this -> mch_id;
		$params['nonce_str'] = $this -> nonce_str;
		if($this->sub_mch_id){
			$params['sub_mch_id'] = $this->sub_mch_id;
		}
		if($this->sub_appid){
			$params['sub_appid'] = $this->sub_appid;
		}
		$params['transaction_id'] = $transaction_id;
		$params['description'] = '分账已完成';
		//获取签名数据
		$params['sign'] = $this -> MakeSignHash($params);
		$xml = $this -> data_to_xml($params);
		$response = $this -> postXmlCurl($xml,self::API_URL_PREFIX.self::PROFITSHARINGFINISH_URL,true);
		return $this -> xml_to_data($response);
	}
	
	
	/**
	 * 关闭订单
	 * @param $out_trade_no 订单号
	 * @return array
	 */
	public function closeOrder($out_trade_no) {
		$this -> params['appid'] = $this -> appid;
		$this -> params['mch_id'] = $this -> mch_id;
		$this -> params['nonce_str'] = $this -> genRandomString();
		$this -> params['out_trade_no'] = $out_trade_no;
		//获取签名数据
		$this -> params['sign'] = $this -> MakeSign($this -> params);
		$xml = $this -> data_to_xml($this -> params);
		$response = $this -> postXmlCurl($xml, self::API_URL_PREFIX . self::CLOSEORDER_URL);
		if (!$response) {
			return false;
		}
		$result = $this -> xml_to_data($response);
		return $result;
	}
	
	/**
     * 微信退款
     * @param string $orderNo
     * @param string $refundNo
     * @param float  $totalFee
     * @param float  $refundFee
     * @param string $opUserId
     * @param string $type
     * @param string $refundAccount
     * @param string $refundReason
     * @return Collection
     */
    public function refund($params) {
		$this -> out_trade_no = $params['out_trade_no'];
		$this -> total_fee = $params['total_fee'];
		$this -> trade_type = $params['trade_type'];
		$this -> params['appid'] = $this -> appid;
		$this -> params['mch_id'] = $this -> mch_id;
		$this -> params['nonce_str'] = $this -> genRandomString();
		$this -> params['out_refund_no'] = $this -> out_trade_no;
		$this -> params['out_trade_no'] = $this -> out_trade_no;
		$this -> params['refund_fee'] = $this -> total_fee;
		$this -> params['total_fee'] =   $this -> total_fee;
		$this -> params['notify_url'] = $this -> notify_url;
		//获取签名数据
		$this -> sign = $this -> MakeSign($this -> params);
		$this -> params['sign'] = $this -> sign;
		$xml = $this -> data_to_xml($this -> params);
		$response = $this -> postXmlCurl($xml, self::API_URL_PREFIX . self::API_REFUND,true);
		if (!$response) {
			$result['result_code'] == 'FAIL';
			$result['err_code'] = '';
			$result['err_msg'] = "错误，请检查支付证书是否有效！";
			return $result;
		}
		$result = $this -> xml_to_data($response);
		if ($result['result_code'] == 'FAIL' && !empty($result['err_code'])) {
			$result['err_msg'] = $result['err_code_des'];
		}
		return $result;
    }


	/**
     * 微信商户提现到微信
     * @param string $orderNo
     * @param string $refundNo
     * @param float  $totalFee
     * @param float  $refundFee
     * @param string $opUserId
     * @param string $type
     * @param string $refundAccount
     * @param string $refundReason
     * @return Collection
     */
    public function payWx($params) {
		$this -> params['mch_appid'] = $this -> appid;
		$this -> params['mchid'] = $this -> mch_id;
		$this -> params['nonce_str'] = $this -> genRandomString();
		$this -> params['partner_trade_no'] = $params['out_trade_no'];
		$this -> params['openid'] = $params['openid'];
		$this -> params['check_name'] = $params['check_name'] ?: 'NO_CHECK'; //'FORCE_CHECK'
		$this -> params['re_user_name'] = $params['user_name'];
		$this -> params['amount'] = $params['total_fee'];
		$this -> params['desc'] = $params['desc'];
		//获取签名数据
		$this -> sign = $this -> MakeSign($this -> params);
		$this -> params['sign'] = $this -> sign;
		$xml = $this -> data_to_xml($this -> params);
		$response = $this -> postXmlCurl($xml, self::API_URL_PREFIX . self::API_TRANSFERS,true);
		if (!$response) {
			$result['result_code'] == 'FAIL';
			$result['err_code'] = '00000';
			$result['err_msg'] = "错误，请检查支付证书是否有效！";
			return $result;
		}
		$result = $this -> xml_to_data($response);
		if ($result['result_code'] == 'FAIL' && !empty($result['err_code'])) {
			$result['err_msg'] = $result['err_code_des'];
		}
		return $result;
    }
	
	
	/**
     * 微信商户提现到银行
     * @return Collection
     */
    public function payBank($params) {
		$this -> params['mch_appid'] = $this -> appid;
		$this -> params['mch_id'] = $this -> mch_id;
		$this -> params['nonce_str'] = $this -> genRandomString();
		$this -> params['partner_trade_no'] = $params['out_trade_no'];
		$this -> params['enc_true_name'] = $this->publicEncrypt($params['user_name']); 
		$this -> params['enc_bank_no'] = $this->publicEncrypt($params['bank_name']);
		$this -> params['bank_code'] = $params['bank_code'];
		$this -> params['amount'] = $params['total_fee'];
		$this -> params['desc'] = $params['desc'];
		//获取签名数据
		$this -> sign = $this -> MakeSign($this -> params);
		$this -> params['sign'] = $this -> sign;
		$xml = $this -> data_to_xml($this -> params);
		$response = $this -> postXmlCurl($xml, self::API_URL_PREFIX . self::API_PAY_BANK,true);
		if (!$response) {
			$result['result_code'] == 'FAIL';
			$result['err_code'] = '00000';
			$result['err_msg'] = "错误，请检查支付证书是否有效！";
			return $result;
		}
		$result = $this -> xml_to_data($response);
		if ($result['result_code'] == 'FAIL' && !empty($result['err_code'])) {
			$result['err_msg'] = $result['err_code_des'];
		}
		return $result;
    }
	
	/*
   * 获取公钥,格式为PKCS#1 转PKCS#8
   * openssl rsa -RSAPublicKey_in -in pubkey.pem -pubout > newpubkey.pem
   * */
	public  function get_pub_key() {
		$params['mch_id'] = $this -> mch_id;
		$params['nonce_str'] = $this -> genRandomString();
		$params['sign'] = $this -> MakeSign($params);
		$xml = $this -> data_to_xml($params);
		$response = $this -> postXmlCurl($xml, self::API_GETPUBLICKEY,true);
		if (!$response) {
			$result['result_code'] == 'FAIL';
			$result['err_code'] = '00000';
			$result['err_msg'] = "错误，请检查支付证书是否有效！";
			return $result;
		}
		$result = $this -> xml_to_data($response);
		if ($result['return_code'] == 'FAIL' || isset($result['err_code']) ) {
			throw new \think\Exception( $result['return_msg'] );
		}
		file_put_contents($this->PUBKEY ,$result['pub_key']);
        return $result['pub_key'];
	}
	
	
	/**
	 * 公钥加密，银行卡号和姓名需要RSA算法加密
	 * @param string $data  需要加密的字符串，银行卡/姓名
	 * @return null|string  加密后的字符串
	 */
	private  function publicEncrypt($data) {
	    // 进行加密
	    $public_key = file_get_contents($this->NEW_PUBKEY);
		if(!$public_key){ $public_key = $this->get_pub_key(); }
	    $encrypted = '';
	    $r = openssl_public_encrypt($data,$encrypted,$public_key,OPENSSL_PKCS1_OAEP_PADDING);
	    if($r){//加密成功，返回base64编码的字符串
	        return base64_encode($encrypted.$encrypted);
	    }else{
	        return false;
	    }
//	    $public_key = file_get_contents($this->PUBKEY);
//	    $rsa = new RSA($public_key,'');
	}
	
	
	/**
	 *
	 * 获取支付结果通知数据
	 * return array
	 */
	public function getNotifyData() {
		//获取通知的数据
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$data = array();
		if (empty($xml)) {
			return false;
		}
		$data = $this -> xml_to_data($xml);
		if (!empty($data['return_code'])) {
			if ($data['return_code'] == 'FAIL') {
				return false;
			}
		}
		return $data;
	}

	/**
	 * 接收通知成功后应答输出XML数据
	 * @param string $xml
	 */
	public function replyNotify() {
		$data['return_code'] = 'SUCCESS';
		$data['return_msg'] = 'OK';
		$xml = $this -> data_to_xml($data);
		echo $xml;
		die();
	}

	/**
	 * 生成APP端支付参数
	 * @param $prepayid 预支付id
	 */
	public function getAppPayParams($prepayid) {
		$data['appId'] = $this -> appid;
		$data['package'] = "prepay_id=$prepayid";
		$data['nonceStr'] = $this -> genRandomString();
		$data['timeStamp'] = time();
		$data['signType'] = "MD5";
		$data['paySign'] = $this -> MakeSign($data);
		return $data;
	}

	/**
	 * 生成签名
	 * @return 签名
	 */
	public function MakeSign($params) {
		//签名步骤一：按字典序排序数组参数
		ksort($params);
		$string = $this -> ToUrlParams($params);
		//签名步骤二：在string后加入KEY
		$string = $string . "&key=" . $this -> key;
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}
	
	//HMAC-SHA256 签名
	private function MakeSignHash ($data) {
        ksort($data);
        $data = array_filter($data, function ($v, $k) {
            if ($k == "sign" && $v == '' && is_array($v)) {
                return false;
            }
            return true;
        }, ARRAY_FILTER_USE_BOTH);
        $str =  $this -> ToUrlParams($data)."&key=".$this -> key;
        return strtoupper(hash_hmac("sha256",$str, $this -> key));
    }
	

	/**
	 * 将参数拼接为url: key=value&key=value
	 * @param $params
	 * @return string
	 */
	public function ToUrlParams($params) {
		$string = '';
		if (!empty($params)) {
			$array = array();
			foreach ($params as $key => $value) {
				$array[] = $key . '=' . $value;
			}
			$string = implode("&", $array);
		}
		return $string;
	}

	/**
	 * 输出xml字符
	 * @param $params 参数名称
	 * return string 返回组装的xml
	 **/
	public function data_to_xml($params) {
		if (!is_array($params) || count($params) <= 0) {
			return false;
		}
		$xml = "<xml>";
		foreach ($params as $key => $val) {
			if (is_numeric($val)) {
				$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
			} else {
				$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
			}
		}
		$xml .= "</xml>";
		return $xml;
	}

	/**
	 * 将xml转为array
	 * @param string $xml
	 * return array
	 */
	public function xml_to_data($xml) {
		if (!$xml) {
			return false;
		}
		//将XML转为array
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		return $data;
	}

	/**
	 * 获取毫秒级别的时间戳
	 */
	private static function getMillisecond() {
		//获取毫秒的时间戳
		$time = explode(" ", microtime());
		$time = $time[1] . ($time[0] * 1000);
		$time2 = explode(".", $time);
		$time = $time2[0];
		return $time;
	}

	/**
	 * 产生一个指定长度的随机字符串,并返回给用户
	 * @param type $len 产生字符串的长度
	 * @return string 随机字符串
	 */
	private function genRandomString($len = 32) {
		$chars = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
		$charsLen = count($chars) - 1;
		// 将数组打乱
		shuffle($chars);
		$output = "";
		for ($i = 0; $i < $len; $i++) {
			$output .= $chars[mt_rand(0, $charsLen)];
		}
		return $output;
	}

	/**
	 * 以post方式提交xml到对应的接口url
	 *
	 * @param string $xml 需要post的xml数据
	 * @param string $url url
	 * @param bool $useCert 是否需要证书，默认不需要
	 * @param int $second url执行超时时间，默认30s
	 * @throws WxPayException
	 */
	private function postXmlCurl($xml, $url, $useCert = false, $second = 30) {
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		if ($useCert == true) {
			//使用证书：cert 与 key 分别属于两个.pem文件
			curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
			curl_setopt($ch,CURLOPT_SSLCERT, $this->SSLCERT_PATH);
			curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
			curl_setopt($ch,CURLOPT_SSLKEY, $this->SSLKEY_PATH);
		}
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		//运行curl
		$data = curl_exec($ch);
		//返回结果
		if ($data) {
			curl_close($ch);
			return $data;
		} else {
			$error = curl_errno($ch);
			curl_close($ch);
			return false;
		}
	}

	/**
	 * 错误代码
	 * @param $code 服务器输出的错误代码
	 * return string
	 */
	public function error_code($code) {
		$errList = array(
			'NOAUTH' => '商户未开通此接口权限', 
			'NOTENOUGH' => '用户帐号余额不足',
			'ORDERNOTEXIST' => '订单号不存在', 
			'ORDERPAID' => '商户订单已支付，无需重复操作', 
			'ORDERCLOSED' => '当前订单已关闭，无法支付', 
			'SYSTEMERROR' => '系统错误!系统超时',
			'APPID_NOT_EXIST' => '参数中缺少APPID', 
			'MCHID_NOT_EXIST' => '参数中缺少MCHID', 
			'APPID_MCHID_NOT_MATCH' => 'appid和mch_id不匹配', 
			'LACK_PARAMS' => '缺少必要的请求参数', 
			'OUT_TRADE_NO_USED' => '同一笔交易不能多次提交', 
			'SIGNERROR' => '参数签名结果不正确', 
			'XML_FORMAT_ERROR' => 'XML格式错误', 
			'REQUIRE_POST_METHOD' => '未使用post传递参数 ', 
			'POST_DATA_EMPTY' => 'post数据不能为空', 
			'NOT_UTF8' => '未使用指定编码格式', 
		);
		if (array_key_exists($code, $errList)) {
			return $errList[$code];
		}
	}

}
